import {boot} from 'quasar/wrappers'
import axios from 'axios'
import {openDB, insertData, deleteData} from 'src/utils/indexedDB'

export default boot(({app}) => {
  app.config.errorHandler = (err, vm, info) => {
    // 处理错误
    console.error('vue error:', err)
    const date = new Date()
    const data = {
      isUpload: true,
      errorMessage: err.stack,
      type: 'vue',
      info,
      robot: '汇众',
      date: date.getTime(),
      dateFormat: `${date.getFullYear()}-${String(
        date.getMonth() + 1
      ).padStart(
        2,
        '0'
      )}-${date.getDate()}  ${date.getHours()}:${date.getMinutes()}:${String(date.getSeconds()).padStart(2, '0')}`
    }
    uploadLog(data)
  }
})

window.addEventListener(
  'error',
  (event) => {
    console.error('addEventListener 捕获到异常：', event)
    const date = new Date()
    const data = {
      isUpload: true,
      errorMessage: event.error.stack,
      type: 'js',
      info: '',
      robot: '汇众',
      date: date.getTime(),
      dateFormat: `${date.getFullYear()}-${String(
        date.getMonth() + 1
      ).padStart(
        2,
        '0'
      )}-${date.getDate()}  ${date.getHours()}:${date.getMinutes()}:${String(date.getSeconds()).padStart(2, '0')}`
    }
    uploadLog(data)
  },
  {
    once: true
  }
)

function saveLog(data) {
  openDB('huizhong', 1)
    .then((db) => {
      return insertData(db, 'log', data)
    })
    .then((db) => {
      console.log('插入数据成功')
      deleteData(db, 'log')
      setTimeout(() => {
        db.close() // 关闭数据库
      }, 2000)
    })
}

function uploadLog(data) {
  // axios.post('http://172.16.2.207:3000/log/upload', data).then(res => {
  axios.post('http://222.71.182.250:8799/log/upload', data).then(res => {
    console.log('上传成功', res)
    // if (res.data.code !== 200) {
    //   console.log('上传失败，保存到本地')
    //   saveLog(data)
    // }
    saveLog(data) // 不管成功还是失败都保存一份到本地
  }).catch(err => {
    console.log('err', err)
    saveLog(data)
  })
}
